package cemp.controller;

import cemp.pay.JsApiOrderModel;
import cemp.pay.Order;
import cemp.pay.WxPayProperties;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
public class PayController {
    @Autowired
    WxPayProperties wxPayProperties;
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/subscribe")
    public void subscribe(@RequestParam(value = "openId") String openId) {
//        String url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
//                "wxbe755cdee15ccfd8",
//                "72ce7874171c1eec85715846edf37c9b");

        String url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
                "wx966597737c7c38fa",
                "de0dea3edda4fe1fd7f4d4fcf2de3564");

        JSONObject response = restTemplate.getForObject(url, JSONObject.class);
        String accessToken = response.getString("access_token");

        //消息订阅
//        String url2 = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
//        Map<String,Object> payload = new HashMap<>();
//        payload.put("touser",openId);
//        payload.put("template_id","2IY8bSwN-Dm4YiAvyy-2PZSSDUweHIdJDy79NJaIH9c");
//        payload.put("page","pages/self/self");

//        Map<String,Object> data = new HashMap<>();
//        data.put("thing2",formParam("subscribe message"));
//        data.put("name3",formParam("saruman"));
//        payload.put("data",data);


        String url2 = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
        Map<String,Object> payload = new HashMap<>();
        payload.put("touser",openId);
        payload.put("template_id","mXzhIn_isPtRFQD4epR9RH6dIxQR-7U-vFZinf3n48I");
        payload.put("page","pages/self/self");


        Map<String,Object> data = new HashMap<>();
        data.put("thing1",formParam("大侠优惠券"));
        data.put("thing3",formParam("提醒到期"));
        data.put("amount4",formParam("100"));
        payload.put("data",data);

        String postJson = JSONUtil.toJsonStr(payload);
        String res = restTemplate.postForObject(url2,postJson,String.class);

        System.out.println("success");
    }

    public HashMap<String,Object> formParam(String value){
        HashMap<String,Object> data = new HashMap<>();
        data.put("value",value);
        return data;
    }


    /**
     * 小程序微信支付的第一步,统一下单
     * V1 版本
     * @return
     * @author lantian
     * @time 2019年4月23日17:36:35
     */
    @GetMapping("/pay")
    public Map createUnifiedOrder() {
        String ip = "127.0.0.1";
        //订单假数据,正式使用中可以通过订单号查询出订单，这里做测试使用
        Order order = new Order();
        order.setMoney(20);
        order.setOrderNum("12313145251");
        order.setOpenid("oV-3C4iM7Wo7B9IrRfCDT8rpsY0I");        //小程序模拟灯虎 使用接口去解析一个openid出来
        //价格
        BigDecimal money = new BigDecimal(order.getMoney());
        Map<String, String> params = JsApiOrderModel
                .builder()
                .appid(wxPayProperties.getAppId())
                .mch_id(wxPayProperties.getMchId())
                // 订单描述
                .nonce_str(order.getOrderNum())
                .body("微信支付")
                // 订单号
                .out_trade_no(order.getOrderNum())
                // 支付金额注意是以分为单位的
                .total_fee(String.valueOf((money.multiply(new BigDecimal("100"))).intValue()))
                //发起订单者ip
                .spbill_create_ip(ip)
                .notify_url(wxPayProperties.getNotifyUrl())
                .trade_type(TradeType.JSAPI.getTradeType())
                .openid(order.getOpenid())
                .build()
                .createSign(wxPayProperties.getMchKey(), SignType.MD5);
        //进行数据加密封装 并发起预支付接口
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
        if (StringUtils.equals(resultMap.get("return_code"), "SUCCESS")) {
            String prepayId = resultMap.get("prepay_id");
            //前端发起支付需要的各种参数
            Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, wxPayProperties.getAppId(),
                    wxPayProperties.getMchKey(), SignType.MD5);
            // 微信浏览器中拿此参数调起支付
            //return new MessageResult(200, "ok", packageParams);
            return packageParams;

        }
        return null;
    }
}
